import socket
import threading
import sys
# TCP是建立可靠连接，并且通信双方都可以以流的形式发送数据。
# 创建 socket 对象
serversocket = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

# 获取本地主机名
host ='192.168.205.1'

port = 9999

# 绑定端口号
serversocket.bind((host, port))

# 设置最大连接数，超过后排队
serversocket.listen(5)

def tcplink(sock,addr):
    msg = '欢迎访问菜鸟教程！' + "\r\n"
    clientsocket.send(msg.encode('utf-8'))
    while True:
        data = sock.recv(1024)
        if not data or data.decode('utf-8') == 'exit':
            break
        sock.send(('Hello, %s!' % data.decode('utf-8')).encode('utf-8'))
    clientsocket.close()
    print('Connection from %s:%s closed.' % addr)

while True:
    # 建立客户端连接
    clientsocket, addr = serversocket.accept()

    print("连接地址: %s" % str(addr))

    # 创建新线程来处理TCP连接:
    t = threading.Thread(target=tcplink, args=(clientsocket, addr))
    t.start()
